package com.weirong.smartvault.backservice.service;

import com.weirong.smartvault.backservice.entity_model.DepartmentModel;
import com.weirong.smartvault.dao.AreaRepository;
import com.weirong.smartvault.dao.DepartmentRepository;
import com.weirong.smartvault.dao.DictRepository;
import com.weirong.smartvault.entity.Area;
import com.weirong.smartvault.entity.Department;
import com.weirong.smartvault.entity.Dict;
import com.weirong.smartvault.backservice.util.common.ListTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 于2017/12/3由 KFEB4 创建 .
 */
@Service
public class DepartmentServiceImpl implements DepartmentService{
    @Autowired
    private AreaRepository areaRepository;

    @Autowired
    private DictRepository dictRepository;

    @Autowired
    private DepartmentRepository departmentRepository;


    @Override
    public void setModelDepartmentAreaSelected(DepartmentModel department, ModelMap model) {
        List<Area> provinces = areaRepository.findAllByParentCode(null);
        Area area = department.getProvince();
        ListTool.moveToTop(provinces,area);
        model.addAttribute("provinces", provinces);
        List<Area> citys = new ArrayList<>();
        area = department.getCity();
        if (area!= null){
            citys = areaRepository.findAllByParentCode(area.getParentCode());
            ListTool.moveToTop(citys,department.getCity());
        }
        model.addAttribute("citys", citys);
        List<Area> villages = new ArrayList<>();
        area = department.getVillage();
        if (area!= null){
            villages= areaRepository.findAllByParentCode(area.getParentCode());
            ListTool.moveToTop(villages,department.getVillage());
        }
        model.addAttribute("villages", villages);
    }

    @Override
    public List<Department> getSuperiorDepartments(DepartmentModel department) {
        String category = department.getType();
        List<Department> departments = getDepartmentsBySubType(category);
        ListTool.moveToTop(departments,department.getSuperiorDepartment());
        return departments;
    }

    @Override
    public List<Department> getDepartmentsBySubType(String category) {
        String superior;
        List<Department> result = new ArrayList<>();
        if (Objects.equals(category, "分行")) {
            return result;
        } else if (Objects.equals(category, "支行")) {
            superior = "分行";
        } else if (Objects.equals(category, "网点"))
            superior = "支行";
        else
            return result;
        Dict dict = dictRepository.findByName(superior);
        result= departmentRepository.findAllByType(dict.getCode());
        return result;
    }
}
